package com.dayu.gulimall.cart.intercepter;

import com.dayu.common.constant.AuthServerConstant;
import com.dayu.common.vo.MemberResponseVo;
import com.dayu.gulimall.cart.constant.CartConstant;
import com.dayu.gulimall.cart.vo.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @author dayu
 * @version 1.0
 * @email dayu007@foxmail.com
 * @date 2021/3/27 12:54
 * @description 在执行方法这之前，判断用户是否登录，并传递给controller目标请求
 */
public class CartIntercepter implements HandlerInterceptor {
    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        MemberResponseVo member = (MemberResponseVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        UserInfoTo cartInfoTo = new UserInfoTo();
        if (member != null) {
            //登录
            cartInfoTo.setUserId(member.getId());
        }

        Cookie[] cookies = request.getCookies();
        if (cookies!=null && cookies.length>0) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if (name.equals(CartConstant.TEMP_USER_COOKIE_NAME)) {
                    cartInfoTo.setUserKey(cookie.getValue());
                }
            }
        }
        if (StringUtils.isEmpty(cartInfoTo.getUserKey())) {
            String uuid = UUID.randomUUID().toString();
            cartInfoTo.setUserKey(uuid);
            cartInfoTo.setTempUser(true);
        }


        threadLocal.set(cartInfoTo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo cartInfoTo = threadLocal.get();
        //如果没有临时用户一定要保存一个临时用户
        if (cartInfoTo.isTempUser()) {
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, cartInfoTo.getUserKey());
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);

        }
    }
}
